package NIO;

import org.apache.tomcat.util.http.fileupload.IOUtils;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.nio.charset.StandardCharsets;

public class SocketHandler implements Runnable{

    private SocketChannel socketChannel;

    public SocketHandler(SocketChannel socketChannel) {
        this.socketChannel = socketChannel;
    }

    @Override
    public void run() {

        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
        try {
            int num;
            while ((num = socketChannel.read(byteBuffer)) > 0) {
                byteBuffer.flip();
                byte[] bytes = new byte[num];
                byteBuffer.get(bytes);

                String s = new String(bytes, "UTF-8");
                System.out.println("收到请求" + s);

                ByteBuffer writeBuff = ByteBuffer.wrap(("已收到请求，请求内容是" + s).getBytes(StandardCharsets.UTF_8));
                socketChannel.write(writeBuff);

                byteBuffer.clear();

            }
        } catch (IOException e) {
            e.printStackTrace();
            IOUtils.closeQuietly(socketChannel);
        }
    }
}
